package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.*;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import com.itheima.web.BaseServlet.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/question")
public class QuestionServlt extends BaseServlet {

    public void toTestUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request, response);
    }

    public void testUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.确认该操作是否支持文件上传 enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            //4.从request中读数据
            List<FileItem> fileItems = upload.parseRequest(request);

            for (FileItem fileItem : fileItems) {
                //5.当前表单是否是文件表单
                if (!fileItem.isFormField()) {
                    //从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"), fileItem.getName()));
                }
            }
        }
    }

    /**
     * 分页查询
     *
     * @param request
     * @param response
     * @return
     */
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        PageInfo<Question> info = questionService.findAll(page, size);
        request.setAttribute("page", info);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request, response);
    }

    /**
     * 跳转到添加界面和用户科目数据回显的方法
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //添加之前需要将学科的信息回显到选择下拉框
        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("companyList", companyList);
        request.setAttribute("catalogList", catalogList);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request, response);
    }

    /**
     * 添加信息的方法
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //1.确认该操作是否支持文件上传 enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            //4.从request中读数据
            List<FileItem> fileItems = upload.parseRequest(request);

            //创建一个标记位,标记当前是否有文件上传操作
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())) {
                    flag = true;
                    break;
                }
            }

            //处理form表单提交过来的数据,将数据获取到,封装成一个对象
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            String picture = questionService.save(question, flag);

            for (FileItem fileItem : fileItems) {
                //5.当前表单是否是文件表单
                if (!fileItem.isFormField()) {
                    //从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"), picture));
                }
            }
        }
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    /**
     * 跳转到修改界面,并回显数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //加载需要修改的数据信息
        String id = request.getParameter("id");
        Question question = questionService.findById(id);
        request.setAttribute("question", question);
        //面试题目属于哪个公司以及属于哪个目录的数据回显
        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("companyList", companyList);
        request.setAttribute("catalogList", catalogList);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request, response);
    }

    /**
     * 修改数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.确认该操作是否支持文件上传 enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            //4.从request中读数据
            List<FileItem> fileItems = upload.parseRequest(request);

            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())) {
                    flag = true;
                    break;
                }
            }

            //处理form表单提交过来的数据,将数据获取到,封装成一个对象
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            questionService.update(question, flag);

            for (FileItem fileItem : fileItems) {
                //5.当前表单是否是文件表单
                if (!fileItem.isFormField()) {
                    //从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"), question.getId()));
                }
            }
        }
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    /**
     * 删除
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        questionService.delete(id);
        response.sendRedirect(request.getContextPath() + "/store/question?operation=list");
    }

    public void toExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //返回的数据文件类型为xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("测试文件名.xlsx".getBytes(), "iso8859-1");
        response.addHeader("Content-Disposition", "attachment;fileName" + fileName);
        /*//生成报告文件,然后传递到前端页面
        ByteArrayOutputStream os = questionService.getReport();
        //获取产生响应流对象
        ServletOutputStream sos = response.getOutputStream();
        //将数据从原始的字节流对象中提取出来写入到servlet对应得输出流中

        os.writeTo(sos);
        sos.flush();
        os.close();*/
        questionService.getReport(response.getOutputStream());
    }

}
